<template>
<div class="app-container calendar-list-container">
  <div class="filter-container">
    <el-input v-if="this.userType === 1" @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="平台编号" v-model="platformId"> </el-input>
    <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="个人客户编号" v-model="listQuery.personalId"> </el-input>
    <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="用户编号" v-model="listQuery.customerId"> </el-input>
    <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
    <el-button class="filter-item"  v-if="personalManager_btn_add"  style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>
    <el-button class="filter-item"   style="margin-left: 10px;color:#999999; background-color:white;border-color:#ececec" @click="handleCreateSecect" type="primary" icon="edit">设置</el-button>
  </div>
  <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
    <el-table-column  align="center" :key="fruit" v-for='fruit in formThead' :label="formTheadName[fruit]" :width="formTheadWidth[fruit]">
      <template slot-scope="scope">
        <div v-if = "fruit === 'authenticationStatus'" width="190" >
          <span v-if="scope.row.authenticationStatus === '00'">未认证</span>
          <span v-if="scope.row.authenticationStatus === '01'">无需认证</span>
          <span v-if="scope.row.authenticationStatus === '02'">认证成功</span>
          <span v-if="scope.row.authenticationStatus === '03'">认证失败</span>
        </div>
        <div v-else-if = "fruit === 'status'" >
          <span v-if="scope.row.status === '00'">正常</span>
          <span v-if="scope.row.status === '01'">冻结</span>
        </div>
        <div v-else >
          {{scope.row[fruit]}}
        </div>
      </template>
    </el-table-column>
    <el-table-column align="center" label="操作" width="300"> <template scope="scope">
        <el-button size="small" type="success" @click="handleDetail(scope.row)">详情</el-button>
        <el-button v-if="personalManager_btn_update" size="small" type="success" @click="handleUpdate(scope.row)">编辑</el-button>
        <el-button v-if="personalManager_btn_del" size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
      </template> </el-table-column>
  </el-table>
  <div v-show="!listLoading" class="pagination-container">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
  </div>
  <el-dialog title="选择" :visible.sync="dialogSelectTableVisible"
    :before-close="handleClose"
  >
    <el-checkbox-group v-model="checkList">
      <el-checkbox label="platformId">平台编号</el-checkbox>
      <el-checkbox label="personalId">个人客户编号</el-checkbox>
      <el-checkbox label="customerId">用户编号</el-checkbox>
      <el-checkbox label="owner" >归属人</el-checkbox>
      <el-checkbox label="thirdNo" >第三方会员编号</el-checkbox>
      <el-checkbox label="realName">用户名称</el-checkbox>
      <el-checkbox label="idCard">身份证号</el-checkbox>
      <el-checkbox label="authenticationStatus">认证状态</el-checkbox>
      <el-checkbox label="status" >账号状态</el-checkbox>
      <el-checkbox label="phone" >手机号</el-checkbox>
      <el-checkbox label="personalLevel" >客户等级</el-checkbox>
      <el-checkbox label="industry">行业</el-checkbox>
      <el-checkbox label="industryDescription">行业描述</el-checkbox>
      <el-checkbox label="job">职务</el-checkbox>
      <el-checkbox label="provinces" >所在省</el-checkbox>
      <el-checkbox label="address" >住址</el-checkbox>
      <el-checkbox label="email" >电子邮件</el-checkbox>
      <el-checkbox label="zipCode" >编号</el-checkbox>
      <el-checkbox label="remark" >备注</el-checkbox>
    </el-checkbox-group>
  </el-dialog>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
    <el-form :model="form" ref="form" :rules="rules">
      <el-form-item v-if="userType === 1" label="平台编号" :label-width="formLabelWidth" prop="platformId">
        <el-select v-model="form.platformId" placeholder="请选择平台">
          <el-option v-for="item in platformOptions" :key="item.platformId" :label="item.platformName" :value="item.platformId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户名称" :label-width="formLabelWidth" prop="realName">
        <el-input style="width:200px;" v-model="form.realName" placeholder="请输入用户名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="身份证号" :label-width="formLabelWidth" prop="idCard">
        <el-input style="width:200px;" v-model="form.idCard" placeholder="请输入身份证号" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="nickName">
        <el-input style="width:200px;" v-model="form.nickName" placeholder="请输入用户昵称" clearable></el-input>
      </el-form-item>
      <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
        <el-select v-model="form.sex" placeholder="请选择性别">
          <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生日" :label-width="formLabelWidth" prop="birthday">
        <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
        <el-input style="width:200px;" v-model="form.phone" placeholder="请输入手机号" clearable></el-input>
      </el-form-item>
      <el-form-item label="客户等级" :label-width="formLabelWidth" prop="personalLevel">
        <el-select v-model="form.personalLevel" placeholder="请选择客户等级">
          <el-option v-for="item in perLevelOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="行业" :label-width="formLabelWidth" prop="industry">
        <el-input style="width:200px;" v-model="form.industry" placeholder="请输入行业" clearable></el-input>
      </el-form-item>
      <el-form-item label="行业描述" :label-width="formLabelWidth" prop="industryDescription">
        <el-input style="width:200px;" v-model="form.industryDescription" placeholder="请输入行业描述" clearable></el-input>
      </el-form-item>
      <el-form-item label="职务" :label-width="formLabelWidth" prop="job">
        <el-input style="width:200px;" v-model="form.job" placeholder="请输入职务" clearable></el-input>
      </el-form-item>
      <el-form-item label="所在省" :label-width="formLabelWidth" prop="provinces">
        <area-select type='text' :level='0' v-model='areaSelected' :data="pca"></area-select>
      </el-form-item>
      <el-form-item label="居住地" :label-width="formLabelWidth" prop="address">
        <el-input style="width:200px;" v-model="form.address" placeholder="请输入居住地" clearable></el-input>
      </el-form-item>
      <el-form-item label="电子邮件" :label-width="formLabelWidth" prop="email">
        <el-input style="width:200px;" v-model="form.email" placeholder="请输入电子邮件" clearable></el-input>
      </el-form-item>
      <el-form-item label="邮编" :label-width="formLabelWidth" prop="zipCode">
        <el-input style="width:200px;" v-model="form.zipCode" placeholder="请输入邮编" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
        <el-input style="width:200px;" v-model="form.remark" placeholder="请输入备注" clearable></el-input>
      </el-form-item>
      <el-form-item label="身份证正面" :label-width="formLabelWidth" prop="idPositive">
        <div class="imgSrc" @click="upIdPositiveUrl">
          <img v-if="form.idPositive" :src="form.idPositive" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </div>
        <input type="file" name="file" id="upload_idPositive" @change="upIdPositive" accept="image/*" style="display: none">
      </el-form-item>
      <el-form-item label="身份证反面" :label-width="formLabelWidth" prop="idNegative">
        <div class="imgSrc" @click="upIdNegativeUrl">
          <img v-if="form.idNegative" :src="form.idNegative" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </div>
        <input type="file" name="file" id="upload_idNegative" @change="upIdNegative" accept="image/*" style="display: none">
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
      <el-button v-else type="primary" @click="update('form')">确 定</el-button>
    </div>
  </el-dialog>

</div>
</template>

<script>
import axios from 'axios'
import { page, getObj, addObj, putObj, delObj, platformPageList, addOrUpdate, queryObj } from '@/api/crm/customers/personalBase'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { pca, pcaa } from 'area-data' // v5 or higher

export default {
  name: 'personals',
  data() {
    return {
      pca,
      pcaa,
      platformId: undefined,
      showColumns: '',
      widthT: '110',
      fruit: '',
      checkList: ['platformId', 'personalId', 'customerId', 'owner', 'thirdNo', 'realName', 'idCard', 'authenticationStatus', 'status', 'phone', 'personalLevel', 'industry', 'industryDescription', 'job', 'provinces', 'address', 'email', 'zipCode', 'remark'],
      formThead: ['platformId', 'personalId', 'customerId', 'owner', 'thirdNo', 'realName', 'idCard', 'authenticationStatus', 'status', 'phone', 'personalLevel', 'industry', 'industryDescription', 'job', 'provinces', 'address', 'email', 'zipCode', 'remark'],
      formTheadName: {
        platformId: '平台编号',
        personalId: '个人客户编号',
        customerId: '用户编号',
        owner: '归属人',
        thirdNo: '第三方会员编号',
        realName: '用户名称',
        idCard: '身份证号',
        authenticationStatus: '认证状态',
        status: '账户状态',
        phone: '手机号',
        personalLevel: '客户等级',
        industry: '行业',
        industryDescription: '行业描述',
        job: '职务',
        provinces: '所在省',
        address: '住址',
        email: '电子邮件',
        zipCode: '邮编',
        remark: '备注'
      },
      formTheadWidth: {
        platformId: '110',
        personalId: '200',
        customerId: '160',
        owner: '110',
        thirdNo: '110',
        realName: '110',
        idCard: '100',
        authenticationStatus: '160',
        status: '110',
        phone: '100',
        personalLevel: '100',
        industry: '100',
        industryDescription: '100',
        job: '100',
        provinces: '100',
        address: '100',
        email: '100',
        zipCode: '100',
        remark: '100'
      },
      listQuery: {
        page: 1,
        limit: 10,
        pageTag: 'personalBase',
        userId: undefined,
        platformId: undefined,
        customerId: undefined,
        personalId: undefined
      },
      addOrUpdate: {
        userId: undefined,
        platformId: undefined,
        pageTag: 'personalBase',
        columns: undefined
      },
      queryObjdata: {
        userId: undefined,
        platformId: undefined,
        pageTag: 'personalBase'
      },
      platformListQuery: {},
      platformOptions: [],
      areaSelected: [],
      form: {},
      list: null,
      selectTypeOptions: [],
      selectStatusOptions: [],
      total: null,
      listLoading: true,
      dialogFormVisible: false,
      dialogSelectTableVisible: false,
      dialogStatus: '',
      personalManager_btn_add: false,
      personalManager_btn_update: false,
      personalManager_btn_del: false,
      textMap: {
        create: '添加',
        update: '修改'
      },
      sexOptions: [{
        value: '1',
        label: '男'
      }, {
        value: '2',
        label: '女'
      }],
      perLevelOptions: [{
        value: 1,
        label: '一级'
      }, {
        value: 2,
        label: '二级'
      }, {
        value: 3,
        label: '三级'
      }],
      tableKey: 0,
      formLabelWidth: '120px',
      rules: {
        platformId: [
          {
            required: true,
            message: '请选择平台编号',
            trigger: 'blur'
          }
        ],
        realName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        idCard: [
          {
            required: true,
            message: '请输入身份证号',
            trigger: 'blur'
          },
          {
            min: 15,
            max: 18,
            message: '长度在 15 到 18 个字符',
            trigger: 'blur'
          }
        ],
        nickName: [
          {
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '长度在 5 到 20 个字符',
            trigger: 'blur'
          }
        ],
        sex: [
          {
            required: true,
            message: '请选择性别',
            trigger: 'blur'
          }
        ],
        birthday: [
          {
            required: true,
            message: '请选择生日',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }
        ],
        personalLevel: [
          {
            required: true,
            message: '请选择客户等级',
            trigger: 'blur'
          }
        ],
        industry: [
          {
            required: true,
            message: '请输入行业',
            trigger: 'blur'
          }
        ],
        industryDescription: [
          {
            required: true,
            message: '请输入行业描述',
            trigger: 'blur'
          }
        ],
        job: [
          {
            required: true,
            message: '请输入职务',
            trigger: 'blur'
          }
        ],
        provinces: [
          {
            required: true,
            message: '请选择所在省',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入电子邮件',
            trigger: 'blur'
          }
        ],
        zipCode: [
          {
            required: true,
            message: '请输入邮编',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        address: [
          {
            required: true,
            message: '请输入居住地',
            trigger: 'blur'
          }
        // ],
        // idPositive: [
        //   {
        //     required: true,
        //     message: '请上传身份证正面',
        //     trigger: 'blur'
        //   }
        // ],
        // idNegative: [
        //   {
        //     required: true,
        //     message: '请上传身份证反面',
        //     trigger: 'blur'
        //   }
        ]
      }
    }
  },
  // watch: {
  //   fruit: function(curVal, oldVal) {
  //     console.log('ioioiioioiioio')
  //     console.log(curVal)
  //     console.log('ioioiioioiioio')
  //   }
  // },
  created() {
    this.queryObj()
    this.getList()
    this.personalManager_btn_add = this.elements['personalManager:btn_add']
    this.personalManager_btn_update = this.elements['personalManager:btn_update']
    this.personalManager_btn_del = this.elements['personalManager:btn_del']
  },
  computed: {
    ...mapGetters([
      'elements',
      'name',
      'userType',
      'userId'
    ])
  },
  watch: {
    checkList(valArr) {
      this.formThead = this.checkList.filter(i => valArr.indexOf(i) >= 0)
      this.key = this.key + 1// 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
    }
  },
  methods: {
    handleClose(done) {
      this.listLoading = true
      this.addOrUpdate.platformId = this.platformId
      this.addOrUpdate.userId = this.userId
      this.addOrUpdate.columns = this.checkList.join(',')
      addOrUpdate(this.addOrUpdate)
        .then(response => {
          this.listLoading = false
          console.log('成功000000000000000000000000000')
        })
      done()
    },
    queryObj() {
      this.listLoading = true
      this.queryObjdata.platformId = this.platformId
      this.queryObjdata.userId = this.userId
      queryObj(this.queryObjdata)
        .then(response => {
          if (response.code === '0000') {
            console.log(response.baseUserTableField)
            if (response.baseUserTableField !== null && response.baseUserTableField !== '' && response.baseUserTableField !== undefined) {
              var showColumnsStr = response.baseUserTableField.columns
              if (showColumnsStr.length !== 0) {
                this.checkList = showColumnsStr.split(',')
                this.formThead = showColumnsStr.split(',')
              }
            }
          }
          this.listLoading = false
        })
    },
    getList() {
      this.listLoading = true
      this.listQuery.platformId = this.platformId
      this.listQuery.userId = this.userId
      if (this.userType === 4) {
        this.listQuery.owner = this.userId
      }
      page(this.listQuery)
        .then(response => {
          this.list = response.body.data.rows
          this.total = response.body.data.total
          this.listLoading = false
          // var showColumnsStr = response.showColumns
          // if (showColumnsStr.length === 0) {
          //   console.log('返回是000000000000000000000')
          // } else {
          //   console.log('返回是1111111111111111111111')
          //   this.checkList = showColumnsStr.split(',')
          //   this.formThead = showColumnsStr.split(',')
          // }
          console.log('sssssssssss')
          console.log(this.list)
        })
    },
    getPlatformPageList() {
      platformPageList(this.platformListQuery)
        .then(response => {
          this.platformOptions = response.data.rows
        })
    },
    handleCreate() {
      this.form = {}
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleCreateSecect() {
      this.dialogStatus = 'Secect'
      this.dialogSelectTableVisible = true
    },
    handleUpdate(row) {
      getObj(row.personalId)
        .then(response => {
          console.log('=====response========================')
          console.log(response)
          this.form = response.personalInfo
          this.areaSelected[0] = this.form.provinces
          this.dialogFormVisible = true
          this.dialogStatus = 'update'
        })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delObj(row.personalId)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
        })
    },
    create(formName) {
      const set = this.$refs
      console.log('addObj=======================================================')
      console.log(this.form)
      this.form.owner = this.userId
      this.form.personalType = '01' // 运营添加用户
      this.form.provinces = this.areaSelected[0]
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form)
            .then(response => {
              console.log(response)
              if (response.code === '0000') {
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '失败',
                  message: '添加失败',
                  type: 'fail',
                  duration: 2000
                })
              }
              this.dialogFormVisible = false
              this.getList()
            })
        } else {
          return false
        }
      })
    },
    update(formName) {
      const set = this.$refs
      this.form.provinces = this.areaSelected[0]
      set[formName].validate(valid => {
        if (valid) {
          putObj(this.form).then(response => {
            console.log('====responseresponse=====================')
            console.log(response)
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.dialogFormVisible = false
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    handleDetail(row) {
      this.$router.push({ path: '/customerManager/personalBaseDetail', query: { personalId: row.personalId }})
    },
    handleFilter() {
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 身份证正面
    upIdPositiveUrl: function() {
      document.getElementById('upload_idPositive').click()
    },
    upIdPositive(event) {
      if (event.target.files.length > 0) {
        this.file = event.target.files[0] // 提交的图片
        console.log(this.file)
        const param = new FormData() // 创建form对象
        param.append('file', this.file)
        const instance = axios.create({
          baseURL: process.env.BASE_API, // api的base_url
          withCredentials: true
        })
        const config = {
          headers: { 'Content-Type': 'multipart/form-data', 'Authorization': getToken() }
        }
        instance.post('/api/crm/upload/file', param, config)
          .then(response => {
            console.log(response.body.data)
            this.form.idPositive = response.body.data.filePath
          })
      }
    },
    // 身份证反面
    upIdNegativeUrl: function() {
      document.getElementById('upload_idNegative').click()
    },
    upIdNegative(event) {
      if (event.target.files.length > 0) {
        this.file = event.target.files[0] // 提交的图片
        console.log(this.file)
        const param = new FormData() // 创建form对象
        param.append('file', this.file)
        const instance = axios.create({
          baseURL: process.env.BASE_API, // api的base_url
          withCredentials: true
        })
        const config = {
          headers: { 'Content-Type': 'multipart/form-data', 'Authorization': getToken() }
        }
        instance.post('/api/crm/upload/file', param, config)
          .then(response => {
            console.log(response.body.data)
            this.form.idNegative = response.body.data.filePath
          })
      }
    }
  }
}
</script>
<style>
.imgSrc {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.filter-item-set {
  background-color: white;
}
.area-select .area-selected-trigger{
  padding: 0px 20px 7px 12px !important;
}
</style>
